class Dao {
    constructor() {
        Bmob.initialize("3f4e46a5fcdacb88c4218d07e0d941be", "78afec8614078083dd61937c5dcb9ed8");
    }

    _def_handler(onSuccess, tag, onFailure) {
        return {
            success: onSuccess,
            error: (error) => {
                console.log(tag + "-失败 ");
                if (onFailure) {
                    onFailure();
                }
            }
        }
    }

    getAllRow(tableName, tag, onSuccess, filter) {
        var Table = Bmob.Object.extend(tableName);
        var queryAll = new Bmob.Query(Table);
        if (filter) {
            filter(queryAll)
        }
        queryAll.find(this._def_handler(onSuccess, tag));
    }

    addOneRow(tableName, data, tag, onSuccess) {
        var RowObject = Bmob.Object.extend(tableName);
        var row = new RowObject();
        Object.keys(data).forEach((key) => {
            row.set(key, data[key])
        });
        row.save(null, this._def_handler(onSuccess, tag));
    }

    getOneRowById(tableName, id, tag, onSuccess, onFailure) {
        var Table = Bmob.Object.extend(tableName);
        var query = new Bmob.Query(Table);
        query.get(id, this._def_handler(onSuccess, tag, onFailure));
    }

    fetchNewRowFromCurRoom(filter, lastMid, tableName, tag, onSuccess, roomId) {
        var Table = Bmob.Object.extend(tableName);
        var queryAll = new Bmob.Query(Table);
        if (filter) {
            filter(queryAll)
        }
        if (lastMid) {
            queryAll.greaterThan("mid", lastMid);
        }
        queryAll.equalTo("roomId", parseInt(roomId));
        queryAll.find(this._def_handler(onSuccess, tag));
    }

    updateRow(id, tableName, data, tag, onSuccess) {
        this.getOneRowById(tableName, id, tag, (row) => {
            Object.keys(data).forEach((key) => {
                row.set(key, data[key]);
            });
            row.save();
            onSuccess()
        })
    }
}